<?php
namespace App\Http\Controllers\Api;

use App\Models\User;
use Illuminate\Http\Request;
use App\Transformers\UserTransformer;
use App\Http\Requests\Api\UserRequest;
use App\Models\Image;
use App\Models\Movie;
use App\Transformers\MovieTransformer;
use App\Models\UserSetting;

class UsersController extends Controller
{
    public function me()
    {
        $user = User::where('id', $this->user()->id)->CollectCount()->followersCount()->followingsCount()->moviesCount()->first();
        return $this->response->item($user, new UserTransformer());
    }

    public function show(User $user)
    {
        $setting = $user->setting;
        if ($setting && !$setting->show_index_page
            && $user->id !== $this->user()->id) {
            return $this->response->error('用户设置隐藏主页', 403);
        }
        $isFollowing = false;
        if ($this->user() && $this->user()->isFollowing($user->id)) {
            $isFollowing = true;
        }
        return $this->response->item($user, new UserTransformer)->addMeta('isFollowing', $isFollowing)->addMeta('setting', $setting);
    }
    public function update(UserRequest $request)
    {
        $user = $this->user();

        $attributes = $request->only(['name', 'introduction']);

        if ($request->avatar_image_id) {
            $image = Image::find($request->avatar_image_id);

            $attributes['avatar'] = $image->path;
        }
        $user->update($attributes);

        return $this->response->item($user, new UserTransformer());
    }

    public function watched(Movie $movie, User $user)
    {

        $query = $movie->whereHas('bingeWatchers', function ($query) use ($user) {
            $query->where('user_id', $user->id)->where('status', 'watched');
        })->newUpdated();
        $movies = $query->paginate(10);
        // 解析用户是否看过
        $watchs = $user->watchStatusWithMovies($movies->pluck('id'));

        return $this->response->paginator($movies, new MovieTransformer($watchs));
    }
    public function watching(Movie $movie, User $user)
    {
        $query = $movie->whereHas('bingeWatchers', function ($query) use ($user) {
            $query->where('user_id', $user->id)->where('status', 'watching');
        })->newUpdated();
        $movies = $query->paginate(10);
        $watchs = $user->watchStatusWithMovies($movies->pluck('id'));

        return $this->response->paginator($movies, new MovieTransformer($watchs));
    }
}
